import React, { useEffect, useState } from 'react';
import { Steps, Alert, Space, Button, Form, Radio, InputNumber, Popconfirm, Result,App } from 'antd';
import './ApplyWithdrawal.less';
import WithdrawalInfoBox from '@/components/WithdrawalInfoBox';
import { useModel, history } from '@umijs/max';

const tailLayout = {
  wrapperCol: {
    offset: 2,
    span: 16,
  },
};
const layout = {
  labelCol: {
    span: 0,
  },
  wrapperCol: {
    span: 12,
  },
};

const ApplyWithdrawal = () => {

  const { message } = App.useApp()

  const { isLoading, setIsLoading } = useModel('Global');
  const { GetWithdrawDetail, ApplyWithdraw, CancelWithdraw, InitDetailForReject } = useModel('Withdrawal');

  const [withdrawalFormRef] = Form.useForm();

  const [currentSteps, setCurrentSteps] = useState(0);
  const [pretreatmentData, setPretreatmentData] = useState({});// 提现预加载数据

  const [currentProcessingStatus, setCurrentProcessingStatus] = useState(0); // 当前处理状态

  const [acceptedWithdrawalInfoTop, setAcceptedWithdrawalInfoTop] = useState([]); // 受理提交结果信息

  const [acceptedWithdrawalInfoBottom, setAcceptedWithdrawalInfoBottom] = useState([]); // 受理提交结果信息

  const statusObj = {
    1: {
      text: '待处理',
      color: '#FD5F02',
    },
    2: {
      text: '已完成',
      color: '#00B42A',
    },
    3: {
      text: '提现拒绝',
      color: '#F53F3F',
    },
  };

  // 提交提现申请
  const handleWithdrawalSubmit = async (values) => {
    let { merchant_id, account_list } = pretreatmentData;
    let alipay_name = account_list.find((item) => item.alipay_account === values.alipay_account).alipay_name;

    let params = {
      ...values,
      merchant_id,
      alipay_name,
    };

    const res = await ApplyWithdraw(params);

    if (res) {
      setCurrentSteps(1);
      await getWithdrawalData();
      message.success('提交成功,请耐心等待平台审核~ ');
    }
  };

  // 判断是否是对象
  const isObject = (obj) => {
    return Object.prototype.toString.call(obj) === '[object Object]';
  };

  // 获取提现预加载数据
  /**
   * @param reapply  是否是重新申请
   */
  const getWithdrawalData = async (reapply) => {
    setIsLoading(true);
    let res = reapply ? await InitDetailForReject() : await GetWithdrawDetail();
    if (res) {

      if (res && res.withdraw_info && isObject(res.withdraw_info)) {
        let {
          withdraw_info: {
            account,
            alipay_account,
            alipay_name,
            amount,
            created_at,
            deal_user,
            deal_voucher,
            deal_time,
            status,
          },
        } = res;

        setAcceptedWithdrawalInfoTop([
          {
            name: '提现金额',
            value: status === 1 ? amount + '元(提现冻结中)' : amount + '元',
            color: '#165DFF',
          },
          {
            name: '收款账户',
            value: account,
          },
          {
            name: '收款账号',
            value: alipay_account,
          },
          {
            name: '收款人姓名',
            value: alipay_name,
          },
          {
            name: '提交信息',
            value: created_at,
          },
        ]);

        let tempArr = [
          {
            name: '处理结果',
            value: statusObj[status].text,
            color: statusObj[status].color,
          },
          {
            name: '处理时间',
            value: deal_time ? deal_time : '-',
          },
        ];

        if (status === 2 || status === 3) {
          tempArr = [
            ...tempArr,
            {
              name: '处理人',
              value: deal_user,
            },
            {
              name: status === 2 ? '处理凭证' : '拒绝原因',
              value: deal_voucher,
              status: status === 2 ? 'success' : 'error',
            },
          ];
        }

        setAcceptedWithdrawalInfoBottom(tempArr);
      }

      // wd_flag = 0 未提现过   wd_flag = 1 提现中
      // status   1 待处理  2 提现完成  3 提现拒绝  4 商户取消

      if (res.wd_flag === 0) {

        setCurrentSteps(0);
        withdrawalFormRef.setFieldsValue({
          alipay_account: res.account_list[0].alipay_account,
        });

      } else if (res.wd_flag === 1 && res.withdraw_info.status === 1) {

        setCurrentSteps(1);

      } else if (res.withdraw_info.status === 2 || res.withdraw_info.status === 3) {

        setCurrentSteps(2);

        let {
          withdraw_info: { status },
        } = res;

        setCurrentProcessingStatus(status);
      }

      setPretreatmentData(res);
      setIsLoading(false);
    }
  };

  // 取消提现
  const cancelWithdrawal = async () => {
    let { id } = pretreatmentData;
    let res = await CancelWithdraw({ id });
    if (res) {
      message.success('取消成功');
      setCurrentSteps(0);
      await getWithdrawalData();
    }
  };

  // 重新申请
  const handleAgainWithdrawal = async () => {
    await getWithdrawalData(true);
    message.success('处理成功');
  };

  // 返回列表
  const gotoWithdrawalList = () => {
    history.push('/cashWithdrawal');
  };

  // 跳转到绑定支付宝页面
  const gotoStores = () => {
    history.push('/stores');
  };

  useEffect(() => {
    getWithdrawalData();
  }, []);

  return (
    <div className='apply_withdrawal'>
      <div className='apply_withdrawal_content'>
        <Steps
          current={currentSteps}
          items={[
            {
              title: '提交申请',
              description: '提交提现申请',
            },
            {
              title: '平台受理',
              description: '等待平处理提现申请',
            },
            {
              title: '提现结果',
              description: '提现申请的处理结果',
            },
          ]}
        />

        {
          currentSteps === 0 && <div className='audit_box'>
            <div className='apply_withdrawal_alert'>
              <Alert
                description={
                  <Space>
                    <div className='alert_info'>
                      <div className='alert_info_title'>提现说明</div>
                      <p>
                        1. 每天累计可提现
                        <span className={'alert_info_orange'}> 1 </span>
                        次,每次允许提现最低金额为
                        <span className={'alert_info_orange'}> 100元 </span>
                        ，金额可精确到分。
                      </p>
                      <p>2. 暂仅支持提现至支付宝，若尚未绑定支付宝账号，请
                        <span
                          className={'alert_info_blur'}
                          onClick={() => gotoStores()}
                        >
                          点击此处
                        </span>
                        前往绑定。</p>
                    </div>
                  </Space>
                }
                type='warning'
                showIcon
                banner />
              <Alert
                className={'alert_money_box'}
                description={
                  <Space>
                    <div className='alert_money'>
                      <div>可提现金额 : <span>{pretreatmentData.withdrawal_available}元</span></div>
                      <div>提现冻结中 : <span>{pretreatmentData.withdrawal_freeze}元</span></div>
                    </div>
                  </Space>
                }
                type='info'
                showIcon
                banner
              />
            </div>
            <Form
              {...layout}
              form={withdrawalFormRef}
              name='withdrawal'
              onFinish={handleWithdrawalSubmit}
            >

              <Form.Item
                name='alipay_account'
                label='收款账户'
                rules={[
                  { required: true, message: '请选择收款账户!' },
                ]}
              >
                {
                  pretreatmentData &&
                  pretreatmentData.account_list &&
                  pretreatmentData.account_list[0].alipay_account ?
                    <Radio.Group>
                      <Space direction='vertical'>
                        {
                          pretreatmentData.account_list.map((item) => (
                            <Radio
                              key={item.alipay_account}
                              value={item.alipay_account}>
                              {item.alipay_account} ({item.alipay_name})
                            </Radio>
                          ))}
                      </Space>
                    </Radio.Group>
                    :
                    <div><a onClick={() => gotoStores()}>去绑定</a></div>
                }
              </Form.Item>

              <Form.Item
                name='withdraw_amount'
                label='提现金额'
                rules={[
                  { required: true, message: '请输入提现金额!' },
                ]}
              >
                <InputNumber
                  placeholder='请输入提现金额'
                  addonAfter={'元'}
                  min={100}
                />
              </Form.Item>
              <Form.Item {...tailLayout}>
                <Button type='primary' htmlType='submit'>
                  确认提现
                </Button>
              </Form.Item>
            </Form>

          </div>
        }

        {
          currentSteps === 1 && <div className='handle_box'>
            <div className='apply_withdrawal_alert'>
              <Alert
                description={
                  <Space>
                    <div className='alert_info'>
                      <div className='alert_info_title'>提现说明</div>
                      <p>1.平台已受理您的提现申请，若审核未通过，提现金额将返还可提现账户中。</p>
                      <p>2.若长时间未处理提现申请，请及时联系平台方面人员</p>
                    </div>
                  </Space>
                }
                type='warning'
                showIcon
                banner />
              <Alert
                className={'alert_money_box'}
                description={
                  <Space>
                    <div className='alert_money'>
                      <div>可提现金额 : <span>{pretreatmentData.withdrawal_available}元</span></div>
                      <div>提现冻结中 : <span>{pretreatmentData.withdrawal_freeze}元</span></div>
                    </div>
                  </Space>
                }
                type='info'
                showIcon
                banner
              />
            </div>

            <div className='handle_box_content'>
              <WithdrawalInfoBox
                title={'提交信息'}
                list={acceptedWithdrawalInfoTop}
              />
              <div style={{ marginTop: '40px' }}>
                <WithdrawalInfoBox
                  title={'受理情况'}
                  list={acceptedWithdrawalInfoBottom}
                />
              </div>
            </div>
            <div className='btn_box'>
              <Popconfirm
                title='您确认取消提现吗?'
                onConfirm={cancelWithdrawal}
                okText='确认'
                cancelText='取消'
              >
                <Button type='primary'>取消提现</Button>
              </Popconfirm>
              <Button onClick={() => gotoWithdrawalList()}>返回列表</Button>
            </div>
          </div>
        }

        {
          currentSteps === 2 && <div className='result_box'>
            <Result
              status={currentProcessingStatus === 2 ? 'success' : 'error'}
              title={currentProcessingStatus === 2 ? '处理完成' : '拒绝提现'}
              subTitle={
                currentProcessingStatus === 2 ? '提现申请已经处理完成' : '平台未通过您的提现申请，如有疑问请于平台方沟通'
              }
            />

            <div className='handle_box_content'>
              <WithdrawalInfoBox
                title={'提交信息'}
                list={acceptedWithdrawalInfoTop}
              />
              <div style={{ marginTop: '40px' }}>
                <WithdrawalInfoBox
                  title={'受理情况'}
                  list={acceptedWithdrawalInfoBottom}
                />
              </div>
            </div>
            <div className='btn_box'>
              {
                currentProcessingStatus === 3 &&
                <Button type='primary' onClick={() => handleAgainWithdrawal()}>重新申请</Button>
              }
              <Button onClick={() => gotoWithdrawalList()}>返回列表</Button>
            </div>

          </div>
        }

      </div>

    </div>
  );
};
export default ApplyWithdrawal;